# -*- coding: utf-8 -*-
"""
Web framework/Tornado RequestHandler Class/test05.py
"""
import tornado.web
import asyncio


class IndexHandler(tornado.web.RequestHandler):
    def prepare(self):
        self.m_method = self.request.method

    def get(self):
        """
        RequestHandler.set_status
        :return:
        """
        r_message = f"This is {self.m_method} method."
        self.set_status(status_code=400, reason="Set Status")
        print(r_message)
        return self.write(r_message)
        # > Postman: GET http://127.0.0.1:8888/
        # > Http Response: This is GET method.
        # > Http Response Status: 400 Set Status

    def post(self):
        """
        RequestHandler.set_header
        :return:
        """
        r_message = f"This is {self.m_method} method."
        self.set_header("X-Code", "1234")
        self.set_header("X-Code", "12343")
        print(r_message)
        return self.write(r_message)
        # > Postman: POST http://127.0.0.1:8888/
        # > Http Response: This is POST method.
        # > Http Response Headers:
        # X-Code: 12343

    def put(self):
        """
        RequestHandler.add_header
        :return:
        """
        r_message = f"This is {self.m_method} method."
        self.add_header("X-Code", "1234")
        self.add_header("X-Code", "12345")
        print(r_message)
        return self.write(r_message)
        # > Postman: PUT http://127.0.0.1:8888/
        # > Http Response: This is PUT method.
        # > Http Response Headers:
        # X-Code: 1234
        # X-Code: 12345

    def delete(self):
        """
        RequestHandler.clear_header
        :return:
        """
        r_message = f"This is {self.m_method} method."
        self.add_header("X-Code", "1234")
        self.add_header("X-Code", "12345")
        self.clear_header("X-Code")
        print(r_message)
        return self.write(r_message)
        # > Postman: DELETE http://127.0.0.1:8888/
        # > Http Response: This is DELETE method.
        # > Http Response Headers:


class WriteHandler(tornado.web.RequestHandler):
    def prepare(self):
        self.m_method = self.request.method

    def get(self):
        """
        RequestHandler.write string
        :return:
        """
        r_message = f"This is {self.m_method} method."
        print(r_message)
        return self.write(r_message)
        # > Postman: GET http://127.0.0.1:8888/write
        # > Http Response: This is GET method.
        # > Http Response Headers:
        # Content-Type: text/html; charset=UTF-8

    def post(self):
        """
        RequestHandler.write dict
        :return:
        """
        dict_res = {
            "method": self.m_method
        }
        return self.write(dict_res)
        # > Postman: POST http://127.0.0.1:8888/write
        # > Http Response: {
        #     "method": "POST"
        # }
        # > Http Response Headers:
        # Content-Type: application/json; charset=UTF-8

    def put(self):
        """
        RequestHandler.write list
        :return:
        """
        list_res = [self.m_method]
        return self.write(list_res)
        # > write() only accepts bytes, unicode, and dict objects. Lists not accepted for security reasons;

    def delete(self):
        """
        RequestHandler.flush
        RequestHandler.finish
        :return:
        """
        r_message = f"This is {self.m_method} method."
        print(r_message)
        self.write(r_message)
        self.flush()
        self.write(r_message + "Go")
        self.finish()
        # > Postman: DELETE http://127.0.0.1:8888/write
        # > Http Response: This is DELETE method.This is DELETE method.Go


class RenderHandler(tornado.web.RequestHandler):
    def get(self):
        """
        RequestHandler.render
        :return:
        """
        self.render("./static/test05.html")

    def post(self):
        """
        RequestHandler.get_template_namespace
        :return:
        """
        print(self.get_template_namespace())
        # > Postman: POST http://127.0.0.1:8888/render
        # > {'handler': <__main__.RenderHandler object at 0x000002ACE6134EB0>,
        # 'request': HTTPServerRequest(protocol='http', host='127.0.0.1:8888',
        # method='POST', uri='/render', version='HTTP/1.1', remote_ip='127.0.0.1'),
        # 'current_user': None, 'locale': <tornado.locale.CSVLocale object at 0x000002ACE6134E50>,
        # '_': <bound method CSVLocale.translate of <tornado.locale.CSVLocale object at 0x000002ACE6134E50>>,
        # 'pgettext': <bound method CSVLocale.pgettext of <tornado.locale.CSVLocale object at 0x000002ACE6134E50>>,
        # 'static_url': <bound method RequestHandler.static_url of
        # <__main__.RenderHandler object at 0x000002ACE6134EB0>>,
        # 'xsrf_form_html': <bound method RequestHandler.xsrf_form_html of
        # <__main__.RenderHandler object at 0x000002ACE6134EB0>>,
        # 'reverse_url': <bound method RequestHandler.reverse_url of
        # <__main__.RenderHandler object at 0x000002ACE6134EB0>>,
        # '_tt_modules': <tornado.web._UIModuleNamespace object at 0x000002ACE6134CA0>,
        # 'modules': <tornado.web._UIModuleNamespace object at 0x000002ACE6134CA0>}

    def delete(self):
        """
        RequestHandler.redirect
        :return:
        """
        self.redirect("/render")
        # > Postman: DELETE http://127.0.0.1:8888/render
        # > HTTP Response: <!DOCTYPE html>
        # <html lang="en">
        # <head>
        # <meta charset="UTF-8">
        # <title>Title</title>
        # </head>
        # <body>
        # Test 05 RenderHandler
        # </body>
        # </html>


class ErrorHandler(tornado.web.RequestHandler):
    def prepare(self):
        self.m_method = self.request.method

    def get(self):
        """
        RequestHandler.send_error
        :return:
        """
        self.send_error(status_code=400)
        self.flush()
        # > Postman: GET http://127.0.0.1:8888/error
        # > HTTP Response: <html><title>400: Bad Request</title><body>400: Bad Request</body></html>
        r_message = f"This is {self.m_method} method."
        # self.write(r_message)
        # > RuntimeError: Cannot write() after finish()

    def post(self):
        """
        RequestHandler.write_error
        :return:
        """
        self.write_error(status_code=500)
        self.flush()
        # > Postman: POST http://127.0.0.1:8888/error
        # > HTTP Response: <html><title>500: OK</title><body>500: OK</body></html>


async def main():
    app = tornado.web.Application([
        (r'/', IndexHandler),
        (r'/write', WriteHandler),
        (r'/render', RenderHandler),
        (r'/error', ErrorHandler),
    ])
    app.listen(8888)
    await asyncio.Event().wait()


if __name__ == "__main__":
    asyncio.run(main())
